﻿// Copyright (c)  MOKEYISH. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Collections.Generic;

namespace NSQL.LogicalResource
{
    public class LogicalDatabase : ILogicalDatabase
    {
        private readonly List<ILogicalSchema> _schemas = new List<ILogicalSchema>();
        public IReadOnlyList<ILogicalSchema> Schemas => _schemas;
        public void Add(ILogicalSchema schema) => _schemas.Add(schema);

        public void Add(LogicalSchema schema)
        {
            schema.Database = this;
            Add((ILogicalSchema)schema);
        }

        public virtual ILogicalSchema FindSchema(string schemaName)
        {
            return _schemas.Find(o => o.Name == schemaName);
        }

        public virtual ILogicalTable FindTableById(int tableId)
        {
            foreach (var schema in _schemas)
            {
                foreach (var table in schema.Tables)
                {
                    if (table.Id == tableId)
                    {
                        return table;
                    }
                }
            }
            return null;
        }

        public virtual ILogicalColumn FindColumnById(int columnId)
        {
            foreach (var schema in _schemas)
            {
                foreach (var table in schema.Tables)
                {
                    foreach (var column in table.Columns)
                    {
                        if (column.Id == columnId)
                        {
                            return column;
                        }
                    }
                }
            }
            return null;
        }
    }
}